var totalPage;//总页数
var currentPage = 1;//当前页
var pageSize = 5;//一页显示的条数
var isAdd = true;
var selectArr = studentsArr;//筛选市学校之后显示的数组
var arrXs =  getSessionData("studentsArr");
var arrSe =  getSessionData("selectArr");
var arrsc =  getSessionData("schoolArr");
var arrcl =  getSessionData("classArr");
var arrct =  getSessionData("cityArr");
addDelEvent();
hid();

// displayArrEvent(arrSe);
displayArrEvent(arrXs);
addStudentEvent();
menuSelectEvent();
clickInfoEvent();
countData(arrSe);

//分页
bindPage();

//生成页面
function bindPage() {
    var totalSize = arrSe.length;
    totalPage = Math.ceil(totalSize / pageSize);
    if (totalPage < currentPage) {
        currentPage = totalPage;
    }
    $(".xsPage").html("");
    for (var i = 1; i <= totalPage; i++) {
        // $(".xsPage").append(`<button class="xsAddPage">${i}</button>`);
        if(i==currentPage){
            $(".xsPage").append(`<button class="xsAddPage de_pageBtActive">${i}</button>`);
        }else {
            $(".xsPage").append(`<button class="xsAddPage">${i}</button>`);
        }
    }
    // addPageEvent(arrStr);
}
addPageEvent();

function addPageEvent() {
    $(".xsPage").on("click", "button", function () {
        $(".xsPage button").each(function () {
            $(this).attr("class","");        //清空所有按钮的点击class属性
        });
        $(this).addClass("de_pageBtActive");
        currentPage = Number($(this).text());
        displayArrEvent(arrSe);
    })
}
//    学生数组显示的事件
function displayArrEvent(arrStr) {

    $(".tbCard").html('');
    var start = (currentPage - 1) * pageSize;
    start = (start<0)?0:start;
    var end = start + pageSize;
    for (var i = start; i < end && i < arrStr.length; i++) {
            $(".tbCard").append(`<tr>
                    <td><input type="checkbox" class="xsAddInput" data-id="${arrStr[i].id}"></td>
                    <td>${arrStr[i].id}</td>
                    <td>${arrStr[i].name}</td>
                    <td>${arrStr[i].sex}</td>
                    <td>${arrStr[i].cNo}</td>
                    <td>${arrStr[i].State}</td>
                    <td>${arrStr[i].tel}</td>
                    <td>
                    <span class="iconfont icon-bianji xsEdit" data-id="${arrStr[i].id}"></span>
                    <span class="iconfont icon-shanchu xsDel" data-id="${arrStr[i].id}"></span>
                    <span class="iconfont icon-home xsView" data-id="${arrStr[i].id}"></span>
                    </td></tr>`)
        }


}
//学校数组显示的事件
function displaySchoolArrEvent() {
    $(".xsSelectSchool").html('');
    for (var i = 0; i < arrsc.length; i++) {
        $(".xsSelectSchool").append(`<option value="${arrsc[i].id}">${arrsc[i].name}</option>`)
    }
}

//学校改变的事件
$(".xsSelectSchool").change(function () {
    $(".xsSelectClass").html('');
    displayClassArrEvent();
});

//班级数组显示的事件
function displayClassArrEvent(cNo = '') {
    var scId = $(".xsSelectSchool").val();
    for (var i = 0; i < arrcl.length; i++) {
        if (arrcl[i].scid == scId) {
            // if (arrcl[i].id == cNo) {
            //     var selected = 'selected';
            // } else {
            //     var selected = '';
            // }
            var selected = arrcl[i].id == cNo ? 'selected' : '';
            $(".xsSelectClass").append(`<option ${selected} value="${arrcl[i].id}">${arrcl[i].name}</option>`)
        }

    }
}

//头部选择市区
function menuSelectEvent() {
    for (var i = 0; i < arrct.length; i++) {
        $(".xsShiSelect").append(`<option value="${arrct[i].id}">${arrct[i].name}</option>`)
    }
    menuSelectSchoolEvent();
}

//市区改变的事件
$(".xsShiSelect").change(function () {
    $(".xsSchoolSelect").html('');
    menuSelectSchoolEvent();
})

//头部选择对应的学校

function menuSelectSchoolEvent() {
    var cityID = $(".xsShiSelect").val();
    for (var j = 0; j < arrsc.length; j++) {
        if (arrsc[j].cityNo === cityID) {
            $(".xsSchoolSelect").append(`<option value="${arrsc[j].id}">${arrsc[j].name}</option>`)
        }
    }
    dispalySelectArrEvent();
}
//
$(".xsShiSelect").change(function (){
    if ($(".xsShiSelect option:selected").text() =="==请选择=="){
        $(".xsSchoolSelect").append(`<option value="wu">==请选择==</option>`);
        // displayArrEvent(arrXs);
    }
})





//根据头部选择的学校循环显示数组selectArr
var isDel = true;
function dispalySelectArrEvent(){
    $(".xsSelectYes").click(function (){
        isDel = false;
        var scid = $(".xsSchoolSelect").val();
         arrSe=[];
        setSessionData("selectArr",arrSe);
        if($(".xsShiSelect option:selected").text() =="==请选择=="){
            // currentPage = 1;
            //arrXs
            arrSe = arrXs;
            displayArrEvent(arrXs);
        }else {
            for(var i =0;i<arrXs.length;i++){
                if(arrXs[i].schoolNo==scid){
                    arrSe.push(arrXs[i]);
                    setSessionData("selectArr",arrSe);
                }
            }
            displayArrEvent(arrSe);
        }
        bindPage();
        countData(arrSe);
    })

}
//添加批量删除事件
function addBatchDelEvent() {
    $('.xsBatch').click( function () {
        $('#myModal2').modal("show");
        flag = -1;
    })
}
//    添加删除事件
var flag = 0
var id,par
function addDelEvent() {
    addBatchDelEvent();
    $('.xsMain').on('click', '.xsDel', function () {
        $('#myModal2').modal("show");
        flag = 0;
        id = $(this).attr("data-id");
        par = $(this).parent().parent();
    })

    $('.xsYesDel').click(function () {
        if(flag === 0){
            //删除行
            par.remove();
            //删除数组
            del(id);
        }else {
            $('.xsAddInput').each(function (index, item) {
                if (item.checked) {
                    var id = $(item).attr("data-id");
                    $(item).parent().parent().remove();
                    del(id);
                }
            })
        }
        //重新生成页面
        bindPage();
        displayArrEvent(arrSe);
    })
}


//模态框点击取消隐藏横态框
function hid() {
    $(".xsCancel").click(function () {
        $('#myModal').modal("hide");
        $('#myModal1').modal("hide");
        $('#myModal2').modal("hide");
        clearForm();
    })
}
//点击出现模态框
function modalShow(){
$(".")
}
//    删除数组函数
function del(id) {
    for (var i = 0; i < arrSe.length; i++) {
        if (arrSe[i].id == id) {
            var content =`删除了学生${arrSe[i].name}`
            setEditInfo(content);
            arrSe.splice(i, 1);
            arrXs.splice(i,1);
            setSessionData("selectArr",arrSe);
            setSessionData("selectArr",arrXs);
            break;
        }
    }
    countData(arrSe);
}
//全选框
$('#xsAllCheck').click(function () {
    var ischeck = this.checked;
    $(".xsAddInput").each(function (index, item) {
        item.checked = ischeck;
    })
})

displaySchoolArrEvent();

//添加事件
function addStudentEvent() {
    $('.xsAddStd').click(function () {
        $('#myModal').modal("show");
        // clearForm();
       isAdd= true;

    })

}

//点击编辑之后出现目前行的值
$(".tbCard").on("click", ".xsEdit", function () {
    isAdd = false;
    var xsId = $(this).data("id");
    $('#myModal').modal("show");

    $.each(arrSe, function (index, item) {
        if (item.id == xsId) {
            $(".xsTableStuName").val(this.name);
            if (this.sex == "男") {
                $(".nan").prop("checked","checked");
            } else if(this.sex == "女"){
                $(".nv").prop("checked","checked");
            }

            $(".xsBirthDate").val(this.birth);
            //$(".xsInputSate").val(this.State);
            if (this.State == "非会员") {
                $(".xsInputUnSate").prop("checked","checked");
            } else {
                $(".xsInputSate").prop("checked","checked");
            }
            var schId = this.schoolNo;//对应学校的id
            $(".xsSelectSchool").html('');
            for (var j = 0; j < arrsc.length; j++) {
                var selected = arrsc[j].id == schId ? 'selected' : '';
                $(".xsSelectSchool").append(`<option ${selected} value="${arrsc[j].id}">${arrsc[j].name}</option>`)
            }
            $(".xsSelectClass").html('');
            displayClassArrEvent(this.cNo);
            $(".xsAddress").val(this.address);
            $(".xsInputTel").val(this.tel);
            $(".xsFatherInputName").val(this.father);
            $(".xsFatherInputTel").val(this.fatherTel);
            $(".xsMotherInputName").val(this.mother);
            $(".xsMotherInputTel").val(this.motherTel);
            $(".xsInputRemark").val(this.note);
            $('.xsAddTab').attr('data-stuid', xsId);
        }
    })
})
getModalValue();

//添加\修改模态框里面点击确定之后的取值函数
function getModalValue() {
    $('.xsYes').click(function () {
        var xsXgId = $('.xsAddTab').attr('data-stuid');
        var a = $('.xsTableStuName').val();//输入的学生姓名
        var b; //输入的性别
        if ($('input[name="sex"]:checked').val() === "nan") {
            b = '男';
        } else {
            b = '女';
        }
        var c = $(".xsBirthDate").val();//输入的日期
        var d = $(".xsSelectClass option:selected").val();//学生选择的班级
        var e = $(".xsAddress").val();//学生的家庭地址
        var f = $(".xsInputTel").val();//学生输入的电话
        var g = $(".xsFatherInputName").val();//学生爸爸的名字
        var h = $(".xsFatherInputTel").val();//学生爸爸的电话
        var i = $(".xsMotherInputName").val();//学生妈妈的名字
        var j = $(".xsMotherInputTel").val();//学生妈妈的电话
        var k = $(".xsInputRemark").val();//学生相关备注
        var l;//学生会员状态
        if ($('input[name="state"]:checked').val() === "member") {
            l = '会员';
        } else {
            l = '非会员';
        }
        var m = $(".xsSelectSchool option:selected").val();//学生所属学校的值
        var str = arrXs[arrXs.length - 1].id;//最后一个学生
        var num = Number(str.split('s')[1]) + 1;//获得最后一个数组的数字再加一
        var xsId;//生成学生的id
        var date = new Date();
        var startDate = new Date(c);
        var newDate = date.getTime() - startDate.getTime();
        var n = Math.ceil(newDate / 1000 / 60 / 60 / 24 / 365) - 1;
        if (num < 10) {
            xsId = "s00" + num;
        } else if (num < 100) {
            xsId = 's0' + num;
        }
        if (isAdd) {
            var obj = {
                id: xsId,
                name: a,
                sex: b,
                age: n,
                cNo: d,
                tel: f,
                schoolNo: m,
                State: l,
                address: e,
                birth: c,
                father: g,
                fatherTel: h,
                mother: i,
                motherTel: j,
                note: k
            }
            arrSe.push(obj);
            arrXs.push(obj);
            var content =`添加了学生${obj.name}`
            setEditInfo(content);
            setSessionData("selectArr",arrSe);
            setSessionData("selectArr",arrXs);
            bindPage();
        } else {
            for(var r=0;r<arrSe.length;r++){
                if(arrSe[r].id == xsXgId){
                    arrSe[r].name = a;
                    arrSe[r].sex = b;
                    arrSe[r].age = n;
                    arrSe[r].cNo = d;
                    arrSe[r].tel = f;
                    arrSe[r].schoolNo =m;
                    arrSe[r].State =l;
                    arrSe[r].birth =c;
                    arrSe[r].father =g;
                    arrSe[r].fatherTel =h;
                    arrSe[r].mother = i;
                    arrSe[r].motherTel = j;
                    arrSe[r].note = k;
                    setSessionData("selectArr",arrSe);
                    var content =`编辑了学生${arrSe[r].name}`
                    setEditInfo(content);
                }
            }
            for(var z=0;z<arrXs.length;z++){
                if(arrXs[z].id == xsXgId){
                    arrXs[z].name = a;
                    arrXs[z].sex = b;
                    arrXs[z].age = n;
                    arrXs[z].cNo = d;
                    arrXs[z].tel = f;
                    arrXs[z].schoolNo =m;
                    arrXs[z].State =l;
                    arrXs[z].birth =c;
                    arrXs[z].father =g;
                    arrXs[z].fatherTel =h;
                    arrXs[z].mother = i;
                    arrXs[z].motherTel = j;
                    arrXs[z].note = k;
                    setSessionData("selectArr",arrXs);
                }
            }
        }
        displayArrEvent(arrSe);
        clearForm();
        countData(arrSe);
    })
}

//清除表单内容
function clearForm() {
    $("#xsForm")[0].reset();
}


//查看事件
function clickInfoEvent() {
    $(".tbCard").on("click", ".xsView", function () {
        $('#myModal1').modal("show");
        var xsId = $(this).data("id");
        for (var i = 0; i < arrSe.length; i++) {
            if (arrSe[i].id == xsId) {
                $(".xsInfoName").text(arrSe[i].name);
                $(".xsInfoSex").text(arrSe[i].sex);
                $(".xsInfoDate").text(arrSe[i].birth);
                $(".xsInfoAge").text(arrSe[i].age);
                var cla = arrSe[i].cNo;
                for (var j = 0; j < arrcl.length; j++) {
                    if (arrcl[j].id == cla) {
                        var num = arrcl[j].name;
                        break;
                    }
                }
                $(".xsInfoClass").text(num);
                $(".xsInfoTel").text(arrSe[i].tel);
                $(".xsInfoAddress").text(arrSe[i].address);
                $(".xsInfoState").text(arrSe[i].State);
                $(".xsInfoFather").text(arrSe[i].father);
                $(".xsInfoFatherTel").text(arrSe[i].fatherTel);
                $(".xsInfoMother").text(arrSe[i].mother);
                $(".xsInfoMotherTel").text(arrSe[i].motherTel);
                $(".xsInfoComment").text(arrSe[i].note);
            }
        }
    })
}

//查看全部数据
function countData(arrt) {
    var len = arrt.length;
    $("#xsAllNumber").text(len);
}
//正则
// inputText();
// function inputText(){
//     var name = /^[\u4e00-\u9fa5]{2,6}$/;
//     var buMen = /^d\d{3}$/;
//     var eTel =/^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
//     check($('.xsZzName'),name);
//     check($('#buMen'),buMen);
//     check($('.xsZzTel'),eTel);
// }
// function check(input,reg){
//     input.blur(function (){
//         if(reg.test( $(this).val())){
//             $(this).next().text('');
//         }else {
//             $(this).next().text('格式有误').css('color','red');
//         }
//     })
//
// }
//
getSessionData()
//得到浏览器中的数据     str:数组名
function getSessionData(str) {
    if(sessionStorage.getItem(str)) {         //浏览器中存在该数组

    }else {         //不存在，初识化
        if(str == "studentsArr"){
            sessionStorage.setItem(str,JSON.stringify(studentsArr));
        }else if(str == "selectArr") {
            sessionStorage.setItem(str,JSON.stringify(selectArr));
        }else if(str == 'schoolArr'){
            sessionStorage.setItem(str,JSON.stringify(schoolArr));
        }else if(str == 'classArr'){
            sessionStorage.setItem(str,JSON.stringify(classArr));
        }else if(str == 'cityArr'){
            sessionStorage.setItem(str,JSON.stringify(cityArr));
        }else if(str = "newNotice"){
            sessionStorage.setItem(str,JSON.stringify(newNotice));
        }
    }
    var obj = JSON.parse(sessionStorage.getItem(str));
    return obj;
}

//将数据存储到浏览器      str:数组名  data:数组
function setSessionData(str,data) {
    var newStr = JSON.stringify(data);
    sessionStorage.setItem(str,newStr);
}
//记录编辑信息方法
// content:编辑内容  例如：content=`修改了${数组名.name}`的信息;
function setEditInfo(content) {
    var obj = getSessionData("newNotice");
    var newObj = new Object();
    newObj.editUser = $(".hz_who").text();         //获取用户的账号
    newObj.editContent = content;
    var lt = new Date().toLocaleDateString();
    var newT = lt.split("/");
    var newStr = "";
    for(var i=0;i<newT.length;i++){
        newStr += newT[i]+"-";
    }
    //设置编辑时间
    newObj.editTime =newStr.substr(0,newStr.length-1);
    obj.push(newObj);
    setSessionData("newNotice",obj);
}